// pages/my/install/mealsTime/mealsTime.js
const call = require('../../../utils/request.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]
    // times:['1:00','2:00','3:00','4:00','5:00','6:00','7:00','8:00','9:00','10:00','11:00','12:00','13:00','14:00','15:00','16:00','17:00','18:00','19:00','20:00','21:00','22:00','23:00','24:00'], //24小时
    times:{
      hours:['00','01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23'],
      hours1:["00时","01时", "02时", "03时", "04时", "05时", "06时", "07时", "08时", "09时", "10时", "11时", "12时", "13时", "14时", "15时", "16时", "17时", "18时", "19时", "20时", "21时", "22时", "23时"],
      mins:[],
      mins1:[]
    },
    timer:{
      morning:null,
      afternoon:null,
      dinner:null,
      sleep:null,
    },
    hasId:false,
    id:{
      morning:null,
      afternoon:null,
      dinner:null,
      sleep:null,
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.init();
    this.getTime();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 初始化页面数据 
   */
  init(){
    //分钟
    let arr = [];
    let arr1 = []
    for(let i=0;i<60;i++){
      arr.push(i<10? '0'+i:i.toString())
      arr1.push(i<10? '0'+i+'分':i+'分')
    }
    this.setData({
      [`times.mins`]:arr,
      [`times.mins1`]:arr1
    })
  },

  /**
   * 选择时间
   */
  bindChange(e){
    const time = e.currentTarget.dataset.time;
    const type = e.currentTarget.dataset.type;
    const id = e.currentTarget.dataset.idx;
    let val = e.detail.value;


    //判断结束时间小于开始时间
    // if(val[0]==val[2] && val[1]<val[3]){
    //   val[3]=(val[1]+1);
    // }else if(val[0]>val[2]){
    //   val[2] = val[0];
    //   val[3]=(val[1]+1);
    // }
    
    //判断结束时间>开始时间
    if(this.isBigTime(`${val[0]}:${val[1]}`,`${val[2]}:${val[3]}`)){
      let time1 = this.getTimeAdd([`${val[0]}:${val[1]}`],60000)
      val[2]=time1[0];
      val[3]=time1[1];
    }

    this.setData({
      [`timer.${time}`]: val
    })
    // let startTime = this.data.times[val[0]].split(':')[0];
    // let endTime = this.data.times[val[1]].split(':')[0];
    // this.setTime(type,startTime,endTime,id)
  },

  /**
   * 判断时间大小
   */
  isBigTime(time1,time2){
    let date1 = '2020-09-04',date2 = '2020-09-05'; //设置时间戳，方便时间转换
    let t1 = new Date(`${date1} ${time1}`).getTime();
    let t2 = new Date(`${date1} ${time2}`).getTime();
    if(time2 == '0:0'){
      t2 = new Date(`${date2} ${time2}`).getTime();
    }
    console.log(time1,time2)
    return t1>=t2;
  },

  /**
   * 获取分钟的前后调整
   */
  getTimeAdd(time,s){
    let times = new Date(new Date(`2020-09-04 ${time}`).getTime()+s);
    let hours = times.getHours();
    let mins = times.getMinutes();
    console.log(time,hours,mins)
    return [hours,mins];
  },

  /**
   * 获取用餐时间段
   */
  getTime(){
    wx.showLoading({
      title: '正在获取数据',
      mask:true
    })
    call.post('/api/system/dining_time').then(res=>{
      wx.hideLoading();
      res = res.data.data;
      console.log("获取用餐时间段",res)
      let data = {}
      let arr = ['morning','afternoon','dinner','sleep']
      let hasId = res[0].id?true:false;
      const hours = this.data.times.hours;
      const mins = this.data.times.mins;
      for(let item of res){
        let a = item.start_time.split(':'),
        b = item.end_time.split(':');
        data = Object.assign(data,{
          [`timer.${arr[item.meals-1]}`]:[hours.indexOf(a[0]),mins.indexOf(a[1]),hours.indexOf(b[0]),mins.indexOf(b[1])],
          [`id.${arr[item.meals-1]}`]:item.id
        })
      }
      data = Object.assign(data,{
        hasId:hasId
      })
      this.setData(data)
    })
  },

  /**
   * 保存 
   */
  save(){
    const timer = this.data.timer;
    const hours = this.data.times.hours;
    const mins = this.data.times.mins;
    const id = this.data.id;

    if(this.isBigTime(`${hours[timer.morning[2]]}:${mins[timer.morning[3]]}`,`${hours[timer.afternoon[0]]}:${mins[timer.afternoon[1]]}`)){
      wx.showToast({
        title: '早餐中餐时间冲突',
        icon:'none'
      })
      return;
    }else if(this.isBigTime(`${hours[timer.afternoon[2]]}:${mins[timer.afternoon[3]]}`,`${hours[timer.dinner[0]]}:${mins[timer.dinner[1]]}`)){
      wx.showToast({
        title: '中餐晚餐时间冲突',
        icon:'none'
      })
      return;
    }else if(this.isBigTime(`${hours[timer.dinner[2]]}:${mins[timer.dinner[3]]}`,`${hours[timer.sleep[0]]}:${mins[timer.sleep[1]]}`)){
      wx.showToast({
        title: '晚餐睡前时间冲突',
        icon:'none'
      })
      return;
    }

    let data = [
      {meals:1,start_time:hours[timer.morning[0]]+':'+ mins[timer.morning[1]],end_time:hours[timer.morning[2]]+':'+ mins[timer.morning[3]]},
      {meals:2,start_time:hours[timer.afternoon[0]]+':'+ mins[timer.afternoon[1]],end_time:hours[timer.afternoon[2]]+':'+ mins[timer.afternoon[3]]},
      {meals:3,start_time:hours[timer.dinner[0]]+':'+ mins[timer.dinner[1]],end_time:hours[timer.dinner[2]]+':'+ mins[timer.dinner[3]]},
      {meals:4,start_time:hours[timer.sleep[0]]+':'+ mins[timer.sleep[1]],end_time:hours[timer.sleep[2]]+':'+ mins[timer.sleep[3]]},
    ]
    if(this.data.hasId){
      data[0].id=id.morning;
      data[1].id=id.afternoon;
      data[2].id=id.dinner;
      data[3].id=id.sleep;
    }
    // console.log(this.data.hasId,data)
    wx.showLoading({
      title: '正在保存',
      mask:true
    })
    call.post('/api/system/set_dining_time',{
      data:JSON.stringify(data)
    }).then(res=>{
      wx.hideLoading();
      console.log("设置用餐时间段",res)
      if(res.statusCode == 200){
        wx.navigateBack({
          delta: 1,
        })
      }
    })
  },

  /**
   * 格式化时间两位数
   */
  timefomat(time){
    return time.toString().length<2?time+'0':time;
  }

  /**
   * 设置用餐时间段
   */
  // setTime(meals,start_time,end_time,id){
  //   let data = {
  //     meals,
  //     start_time,
  //     end_time,
  //   }
  //   if(id){
  //     data = Object.assign(data,{id})
  //   }
  //   console.log(data)
  //   call.post('/api/system/set_dining_time',{
  //     data:JSON.stringify([data])
  //   }).then(res=>{
  //     console.log("设置用餐时间段",res)
  //   })
  // },

})